import { BadRequestException, Injectable } from '@nestjs/common';
import { UserCreateDto, UserListDto, UserUpdateDto } from './dto';
import { UserEntity } from './entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
@Injectable()
export class UserService {
    constructor(@InjectRepository(UserEntity) private userRepository: Repository<UserEntity>) {}

    async create(entity: UserCreateDto) {
        return this.userRepository.save(entity);
    }

    findAll() {
        return `This action returns all user`;
    }
    async list(dto: UserListDto) {
        const { page = 0, psize = 20 } = dto.limit || {};

        return this.userRepository.find({
            where: dto.where,
            order: { createdAt: 'DESC' },
            skip: page * psize,
            take: psize,
        });
    }
    async findById(id: number) {
        const entity = await this.userRepository.findOne(id);

        if (!entity) throw new BadRequestException('数据不存在');
        return entity;
    }

    async update(id: number, update: UserUpdateDto) {
        return this.userRepository.update(id, update);
    }
    async delete(id: number) {
        return this.userRepository.delete({ id });
    }
}
